package com.yuan.zsschool.ui.me;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.yuan.base.framework.BaseFrameworkActivity;
import com.yuan.base.framework.BaseUserManager;
import com.yuan.base.framework.bean.TipResult;
import com.yuan.base.framework.bean.UserInfo;
import com.yuan.base.framework.http.BaseHttpCallBack;
import com.yuan.base.framework.http.BaseHttpRequest;
import com.yuan.base.framework.image.BaseImageLoad;
import com.yuan.base.utils.DialogUtil;
import com.yuan.base.utils.ImageUtil;
import com.yuan.base.utils.PreferencesUtils;
import com.yuan.zsschool.Constant;
import com.yuan.zsschool.R;
import com.yuan.zsschool.Urls;

import java.io.File;
import java.util.HashMap;
import java.util.List;

import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import cn.finalteam.toolsfinal.StringUtils;

/**
 * 个人详情
 */
public class ParentInfoActivity extends BaseFrameworkActivity {

	private final int REQUEST_SELECT_PHOTO = 1;
	private final int REQUEST_TAKE_PHOTO = 2;
	private final int REQUEST_CROP_PHOTO = 3;
	// --------------------------控件--------------------------
	private ImageView iv_user_avatar;
	private EditText et_parent_name;
	private EditText et_parent_id_card;
	private TextView tv_parent_sex;
	private EditText et_phone2;
	private Button btn_submit;
	private ImageView going1;
	// --------------------------变量--------------------------
	private String avatar;
	private boolean isModify = false;

	@Override
	protected int getLayoutId() {
		return R.layout.activity_parent_info;
	}

	@Override
	protected void bindViews() {
		iv_user_avatar = findViewById(R.id.iv_user_avatar);
		et_parent_name = findViewById(R.id.et_parent_name);
		et_parent_id_card = findViewById(R.id.et_parent_id_card);
		tv_parent_sex = findViewById(R.id.tv_parent_sex);
		et_phone2 = findViewById(R.id.et_phone2);
		btn_submit = findViewById(R.id.btn_submit);
		going1 = findViewById(R.id.going1);

		tv_parent_sex.setOnClickListener(v -> selectSex());
		iv_user_avatar.setOnClickListener(v -> selectAvatar());
		setOnClickListener(R.id.btn_edit, v -> {
			TextView edit = (TextView) v;
			if (getStringByUI(edit).equals("取消")) {
				isModify = false;
				init();
				edit.setText("修改");
			} else {
				isModify = true;
				edit.setText("取消");
			}
			changeEdit();
		});
		setOnClickListener(R.id.btn_submit, v -> doSubmit());
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		init();
		changeEdit();
	}

	private void changeEdit() {
		et_parent_name.setEnabled(isModify);
		et_parent_id_card.setEnabled(isModify);
		et_phone2.setEnabled(isModify);
		btn_submit.setVisibility(isModify ? View.VISIBLE : View.GONE);
		going1.setVisibility(isModify ? View.VISIBLE : View.GONE);
	}

	private void init() {
		UserInfo user = BaseUserManager.getUser();
		avatar = user.getSpic();
		BaseImageLoad.loadCircularAvatar(user.getSpic(), iv_user_avatar);
		et_parent_name.setText(user.getName());
		et_parent_id_card.setText(user.getIdCardNo());
		tv_parent_sex.setText(user.getGender());
		et_phone2.setText(TextUtils.isEmpty(user.getPhone2()) ? "" : user.getPhone2());
	}

	private void doSubmit() {
		if (TextUtils.isEmpty(getStringTrimByUI(et_parent_name))) {
			showToast("请填写姓名");
			return;
		}
		if (TextUtils.isEmpty(getStringTrimByUI(et_parent_id_card))) {
			showToast("请填写身份证");
			return;
		}
		HashMap<String, Object> params = new HashMap<>();
		params.put("name", getStringTrimByUI(et_parent_name));
		params.put("idCardNo", getStringTrimByUI(et_parent_id_card));
		params.put("gender", getStringTrimByUI(tv_parent_sex));
		params.put("phone1", PreferencesUtils.getString(this, Constant.Preferences.USER_CODE, ""));
		params.put("phone2", getStringTrimByUI(et_phone2));
		params.put("spic", avatar);
		params.put("mpic", avatar);
		params.put("lpic", avatar);
//		params.put("baiduChannelid", "");
//		params.put("mail", "");
//		params.put("wechat", "");
//		params.put("authorized", BaseUserManager.getUser().isAuthorized());
		BaseHttpRequest.post(Urls.getUrl(Urls.modifyParentInfo), params, new BaseHttpCallBack<TipResult>() {
			@Override
			public void onPost() {
				hideProgressBarAtOnce();
			}

			@Override
			public void onPreStart() {
				showProgressBar("正在提交...");
			}

			@Override
			public void onSuccess(TipResult result) {
				if (result.isSuccess()) {
					UserInfo user = BaseUserManager.getUser();
					user.setName(getStringTrimByUI(et_parent_name));
					user.setIdCardNo(getStringTrimByUI(et_parent_id_card));
					user.setGender(getStringTrimByUI(tv_parent_sex));
					user.setPhone2(getStringTrimByUI(et_phone2));
					user.setLpic(avatar);
					user.setMpic(avatar);
					user.setSpic(avatar);
					BaseUserManager.saveUserInfo(user);
					showToast("修改成功");
					closeSelf();
				} else {
					showToast(result.getMessage());
				}
			}
		});
	}

	private void selectSex() {
		if (!isModify) {
			return;
		}
		String[] sex = new String[]{"男", "女"};
		DialogUtil.select(this, "选择性别", sex, (dialog, which) -> tv_parent_sex.setText(sex[which]));
	}

	private void selectAvatar() {
		if (!isModify) {
			return;
		}
		String[] items = {"拍照", "从相册中选择"};
		DialogUtil.select(this, "请选择图片来源", items, (dialog, which) -> {
			switch (which) {
				case 0:
					// 拍照
					GalleryFinal.openCamera(REQUEST_SELECT_PHOTO, new FunctionConfig.Builder().build(), onHanlderResultCallback);
					break;
				case 1:
					// 本地选取
					GalleryFinal.openGallerySingle(REQUEST_SELECT_PHOTO, new FunctionConfig.Builder().build(), onHanlderResultCallback);
					break;
			}
		}, "取消", null);
	}

	private GalleryFinal.OnHanlderResultCallback onHanlderResultCallback = new GalleryFinal.OnHanlderResultCallback() {
		@Override
		public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {
			switch (reqeustCode) {
				case REQUEST_SELECT_PHOTO:
				case REQUEST_TAKE_PHOTO:
					doCrop(resultList.get(0).getPhotoPath());
					break;
				case REQUEST_CROP_PHOTO:
					upImg(resultList.get(0).getPhotoPath());
					break;
			}
		}

		@Override
		public void onHanlderFailure(int requestCode, String errorMsg) {
//			showToast("图片选择出错");
		}
	};

	private void doCrop(String filePath) {
		new Handler().postDelayed(() -> {
			// 如果callback为null，表示上一个处理流程已经被完全回收掉，必须回收完成才能继续执行crop
			if (GalleryFinal.getCallback() == null) {
				//带配置
				final FunctionConfig functionConfig = new FunctionConfig.Builder()
						.setCropWidth(150)//裁剪宽度
						.setCropHeight(150)//裁剪高度
						.setEnableCrop(true)//开启裁剪功能
						.setCropSquare(true)
						.setForceCrop(true).build();//裁剪正方形
				runOnUiThread(() -> GalleryFinal.openCrop(REQUEST_CROP_PHOTO, functionConfig, ImageUtil.handleRotateRePath(filePath), onHanlderResultCallback));
			} else {
				doCrop(filePath);
			}
		}, 50);
	}

	private void upImg(String filePath) {
		submitAvatar(filePath, this, result -> {
			BaseImageLoad.loadCircularAvatar(result, iv_user_avatar);
			avatar = result;
//			BaseUserManager.getUser().setLpic(result);
//			BaseUserManager.getUser().setMpic(result);
//			BaseUserManager.getUser().setSpic(result);
		});
	}

	private ProgressDialog mProgressDialog;

	public void submitAvatar(final String path, final BaseFrameworkActivity activity, final UploadSuccess onSuccess) {
		File file = new File(path);
		BaseHttpRequest.post(Urls.getUrl(Urls.upload), file, new BaseHttpCallBack<TipResult>() {
			@Override
			public void onLoading(long current, long total) {
				mProgressDialog.setProgress((int) (((float) current / (float) total) * 100));
			}

			@Override
			public void onPreStart() {
				mProgressDialog = new ProgressDialog(activity);
				mProgressDialog.setTitle("正在上传...");
				mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
				mProgressDialog.setMax(100);
				mProgressDialog.setCanceledOnTouchOutside(false);
				mProgressDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, "取消", (dialog, which) -> {
					if (getCancelable() != null) {
						getCancelable().cancel();
					}
				});
				mProgressDialog.show();
			}

			@Override
			public void onSuccess(TipResult result) {
				try {
					mProgressDialog.dismiss();
				} catch (Exception ignored) {
				}
				if (StringUtils.isEmpty(result.getMessage())) {
					activity.showToast("上传失败,请重试");
				} else {
					onSuccess.onSuccess(result.getMessage());
				}
			}

			@Override
			public void onFailure(int code, String msg) {
				activity.showToast("上传失败,请重试");
				try {
					mProgressDialog.dismiss();
				} catch (Exception ignored) {
				}
			}

			@Override
			public void onPost() {
				mProgressDialog = null;
			}
		});
	}

	public interface UploadSuccess {
		void onSuccess(String fileId);
	}

}

